package com.genzou.replacer

import com.genzou.convert.*

class FileReplacer{
    
    final def convertor = new Convertor<File>()
    
    def backupDir = ""
    
    def doBackup = ""
    def doNotInSubdirectories = ""
    def enabled = ""
    def ignoreCase = ""
    def ignoreDotFile = true
    def useRegexp = ""
    def dir = ""
    def encoding = ""
    def excludes = ""
    def includes = ""
    def token = ""
    def replace = ""

    final def COMMON_FILTER = {
        it.file &&
        !(ignoreDotFile && it.path.contains(File.separator + ".")) &&
        it.name.contains(includes) &&
        !(excludes && it.name.contains(excludes))
    }
    
    final def COMMON_BACKUPER = {
        if( doBackup && backupDir ){
            def backup = new File(backupDir + (it.path - dir))
            if( !backup.parentFile.exists() ){
                backup.parentFile.mkdirs()
            }
            backup << it.readBytes()
            backup
        } else {
            it
        }
    }
    
    List<File> replace(){
        def tokenText = token
        
        convertor.clear()
        convertor.filters << COMMON_FILTER
        convertor.backuper = COMMON_BACKUPER
        
        if( useRegexp ){
            tokenText = (ignoreCase?"(?i)":"") + token
            convertor.filters << {
                it.getText(encoding) =~ tokenText
            }
            convertor.convertors << {
                it.write(it.getText(encoding).replaceAll(tokenText, replace), encoding)
                it
            }
        } else {
            convertor.filters << {
                it.getText(encoding).contains(tokenText)
            }
            convertor.convertors << {
                it.write(it.getText(encoding).replace(tokenText, replace), encoding)
                it
            }
        }
        
        def files = []
        new File(dir).eachFileRecurse{
            files << it
        }
        convertor.convert(files)
    }
}